package com.example.javabasic.thread.classtwo.lock.demo1;

//共享数据
public class ShareData {
    //定长char 数组
    private final char[] buffer;
    //读写锁
    private final ReadWriteLock lock = new ReadWriteLock();

    //构造器
    public ShareData(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < size; i++) {
            this.buffer[i] = '*';
        }
    }


    public char[] read() throws InterruptedException {
        try {
            //读锁
            lock.readLock();
            return this.doRead();
        } finally {
            //释放读锁
            lock.readUnlock();
        }
    }

    //读内容
    private char[] doRead() throws InterruptedException {
        char[] newbuf = new char[buffer.length];
        //复制一份传出
        for (int i = 0; i < buffer.length; i++) {
            newbuf[i] = buffer[i];
        }
        Thread.sleep(30);
        return newbuf;
    }


    //写
    public void write(char c) throws InterruptedException {
        try {
            //获取写锁
            lock.writeLock();
            this.doWrite(c);
        } finally {
            lock.writeUnLock();
        }

    }

    //写操作
    private void doWrite(char c) throws InterruptedException {
        for (int i = 0; i < buffer.length; i++) {
            this.buffer[i] = c;
            Thread.sleep(10);
        }
    }


}
